package cn.com.cfae.iras.doc.analyze.components.rationality;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.FormatTimeUtil;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 *内容合理性
 * M-3-1
 * 1、在M-3-1章节抽取起息日期、发行日期，如果起息日>发行日，提示人工核对；
 * 发行阶段
 */
@Component("R1014")
@Scope("prototype")
public class R1014 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(R1014.class);
    @Autowired
    private HandingData handingData;
    @Autowired
    private FormatTimeUtil formatTime;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取R1014组件M");
        List<ComponentResult> componentResults = checkRulesR1014(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取R1014组件BM");
        List<ComponentResult> componentResults = checkRulesR1014(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取R1014组件DM");
        List<ComponentResult> componentResults = checkRulesR1014(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取R1014组件BDM");
        List<ComponentResult> componentResults = checkRulesR1014(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }


    private List<ComponentResult> checkRulesR1014(String model,String catalogId,String chapterId,String ruleName){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;
        int pageNum = 0;
        List<ComponentResult.TextPosition> contentAndPositionList = null;
        boolean flag = false;
        int startPage = 0;
        String qxrText = null;
        String fxrText = null;
        int fxPageNum = 0;
        List<ComponentResult.TextPosition> fxContentAndPositionList = null;
        boolean isAllErr = false;
        boolean isAllSeem = false;
        try {

            if (extractData != null){
                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPage = chapterModel.getStartPage();
                //起息日
                extractItem = getExtractItem(extractData,model,"FXTK","QXR");
                if (extractItem != null){
                    KVText value = extractItem.getValue();
                    KVText key = extractItem.getKey();
                    qxrText = value!=null?value.getText():null;
                    pageNum = value!=null?value.getPageNumber():startPage;
                    contentAndPositionList = key!=null?getContentAndPositionList(key):null;
                }
                if (extractItem==null){
                    ExtractItem jkrExtractItem = getExtractItem(extractData,model,"FXTK","JKR");
                    if (jkrExtractItem!=null){
                        KVText value = jkrExtractItem.getValue();
                        KVText key = jkrExtractItem.getKey();
                        qxrText = value!=null?value.getText():null;
                        pageNum = value!=null?value.getPageNumber():startPage;
                        contentAndPositionList = key!=null?getContentAndPositionList(key):null;
                    }
                }
                pageNum = pageNum!=0?pageNum:startPage;

                //发行日
                extractItem = getExtractItem(extractData,model,"FXTK","FXRQ");
                if (extractItem!=null){
                    KVText value = extractItem.getValue();
                    KVText fxrkey = extractItem.getKey();
                    fxrText = value!=null?value.getText():null;
                    fxPageNum = value!=null?value.getPageNumber():startPage;
                    fxContentAndPositionList = fxrkey!=null?getContentAndPositionList(fxrkey):null;
                }
            }
            if (StringUtils.isNotEmpty(qxrText)){
                componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查-起息日:"+qxrText,"已抽取",false,getRegulationId(), pageNum,contentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查-起息日","未识别,建议人工核对",true,getRegulationId(), pageNum,contentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            if (StringUtils.isNotEmpty(fxrText)){
                componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查-发行日:"+fxrText,"已抽取",false,getRegulationId(), fxPageNum,fxContentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查-发行日","未识别,建议人工核对",true,getRegulationId(), fxPageNum,fxContentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            if (StringUtils.isNotEmpty(qxrText)&&StringUtils.isNotEmpty(fxrText)){
                qxrText = formatTime.formatTime(qxrText);
                fxrText = formatTime.formatTime(fxrText);
                if (qxrText.length()==8&&fxrText.length()==8){
                    long tValue = formatTime.getTimeDValue(fxrText,qxrText,"yyyyMMdd");
                    if (tValue>0){
                        flag = true;
                    }
                }

                if (flag){
                    componentResult = handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查","合理",false,getRegulationId(), pageNum,contentAndPositionList,"01");
                    componentResults.add(componentResult);
                }else {
                    isAllErr = true;
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查","请人工核对",true,getRegulationId(), pageNum,contentAndPositionList,"02");
                    componentResults.add(componentResult);
                }
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查","未识别,建议人工核对",true,getRegulationId(), startPage,contentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            if (isAllErr){
                for (ComponentResult result:componentResults){
                    result.setExist("02");
                }
            }
            if (isAllSeem){
                for (ComponentResult result:componentResults){
                    result.setExist("03");
                }
            }

        }catch (Exception e){
            componentResults.clear();
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"起息日与发行日检查","未识别,建议人工核对",true,getRegulationId(), startPage,contentAndPositionList,"03");
            componentResults.add(componentResult);
            log.error(e.getMessage(),e);
        }
        return  componentResults;
    }

    private ExtractItem getExtractItem(DocumentModel extractData, String chapter, String model, String key){
        ExtractItem extractItem  = null;
        if (extractData!=null){
            ChapterModel chapterModel = extractData.getChapterModel(chapter);
            if (chapterModel != null){
                ExtractBizModel extractMode = chapterModel.getModel(model);
                if (extractMode!=null){
                    extractItem = extractMode.getExtractItem(key);
                }
            }
        }
        return extractItem;
    }

   /* private int formatTime(String str){
        StringBuffer timeBuff = new StringBuffer();
        String regex = "\\d+";
        List<String> times = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()){
            times.add(matcher.group());
        }
        if (CollectionUtils.isNotEmpty(times)){
            if (times.size()<=3){
                for (int i=0;i<times.size();i++){
                    String time = times.get(i);
                    if (time.length()==4)
                        continue;
                    if (time.length()<2){
                        times.set(i,"0"+time);
                    }
                }
                for (String time : times){
                    timeBuff.append(time);
                }

            }else if (times.size()>3&&times.size()<=6){
                for (int i=0;i<times.size();i++){
                    String time = times.get(i);
                    if (time.length()==4)
                        continue;
                    if (time.length()<2){
                        times.set(i,"0"+time);
                    }
                }
                for (int i=0;i<3;i++){
                    timeBuff.append(times.get(i));
                }
            }
        }
        return  Integer.parseInt(timeBuff.toString());
    }*/
}
